package com.cloud.lan.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloud.lan.api.dto.resp.LanUserResp;
import com.cloud.lan.config.cache.LoadingCacheConfiguration;
import com.cloud.lan.dao.LanBadgeCfgMapper;
import com.cloud.lan.dao.LanBadgeUserRecordMapper;
import com.cloud.lan.entity.base.BaseResponse;
import com.cloud.lan.entity.base.ListResponse;
import com.cloud.lan.entity.model.dataobject.LanBadgeCfgDO;
import com.cloud.lan.entity.model.dataobject.LanBadgeUserRecordDO;
import com.cloud.lan.service.ILanBadgeService;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by zhouquan on 2022/5/21.
 */
@Slf4j
@Service
public class LanBadgeServiceImpl implements ILanBadgeService{

    @Resource
    private LoadingCacheConfiguration cacheConfiguration;
    @Resource
    private LanBadgeUserRecordMapper lanBadgeUserRecordMapper;
    @Resource
    private LanBadgeCfgMapper lanBadgeCfgMapper;


    @Override
    public ListResponse<Object> queryUserBadges(String token) {
        LanUserResp lanUserResp = cacheConfiguration.userInfo.getUnchecked(token);
        if(Objects.isNull(lanUserResp)){
            return ListResponse.error(BaseResponse.ERROR_TOKEN_NO,"token无效");
        }

        LambdaQueryWrapper<LanBadgeUserRecordDO> qw = new LambdaQueryWrapper<>();
        qw.eq(LanBadgeUserRecordDO::getUserId,lanUserResp.getUserId());
        qw.orderByDesc(LanBadgeUserRecordDO::getId);
        Page<LanBadgeUserRecordDO> page = new Page<>(1,30);
        IPage<LanBadgeUserRecordDO> pageList = lanBadgeUserRecordMapper.selectPage(page, qw);
        if(ObjectUtil.isNotEmpty(pageList.getRecords())){
            List<LanBadgeCfgDO> cfgDOList = new ArrayList<>();
            pageList.getRecords().stream().forEach(record->{
                LanBadgeCfgDO cfgDO = lanBadgeCfgMapper.selectById(record.getBadgeId());
                if(Objects.nonNull(cfgDO)){
                    cfgDOList.add(cfgDO);
                }
            });
            log.info("userId:[{}] 用户徽章记录:[{}]",lanUserResp.getUserId(), JSON.toJSONString(cfgDOList));
            ListResponse listResponse = ListResponse.success(cfgDOList);
            listResponse.setNums(cfgDOList.size());
            return listResponse;
        }
        return ListResponse.success();

    }
}
